package com.cars.util.request;

import com.cars.util.string.StringUtil;
import org.springframework.util.MimeTypeUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: 孔垂云
 * @version: 1.0
 * @date: 2020/8/11 0:33
 */
public class RequestUtil {
    /**
     * 获取参数
     *
     * @param request
     * @return
     */
    public static String getBody(HttpServletRequest request) {
        System.out.println(request.getMethod());
        String method = request.getMethod();
        if (method.equalsIgnoreCase("get")) {
            return getRequestParams(request);
        } else {
            String body = "";
            try {
                body = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return body;
        }
    }

    /**
     * 获取请求参数
     *
     * @param request 请求
     * @return 参数
     */
    public static String getRequestParams(HttpServletRequest request) {
        String params = "";
        try {
            String contextType = request.getContentType();
            if (!StringUtil.isNotNullOrEmpty(contextType)
                    && contextType.contains(MimeTypeUtils.APPLICATION_JSON_VALUE)) {
                params = StringUtil.getBodyString(request.getReader());
            } else {
                params = StringUtil.getRequestParamMap(request).toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return params;
    }

    /**
     * CLONE inputStream
     *
     * @param inputStream inputStream
     * @return ByteArrayOutputStream
     */
    public static ByteArrayOutputStream cloneInputStream(InputStream inputStream) {

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        try {
            while ((length = inputStream.read(buffer)) > -1) {
                byteArrayOutputStream.write(buffer, 0, length);
            }
            byteArrayOutputStream.flush();
            byteArrayOutputStream.close();
            return byteArrayOutputStream;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
